#pragma once
#include"vector.h"

namespace fengxi
{
	template<class T>
	class Less
	{
	public:
		bool operator()(const T& x1, const T& x2)
		{
			return x1 < x2;
		}
	};

	template<class T>
	class Greater
	{
	public:
		bool operator()(const T& x, const T& y)
		{
			return x > y;
		}
	};

	template<class T,class Container = vector<T>,class Compare = Less<T>>
	class priority_queue
	{
	public:
		priority_queue()
		{}
		void AdjustDown(int parent)
		{
			Compare com;

			int child = parent * 2 + 1;
			while (child < _con.size())
			{
				//if (child + 1 < _con.size() && _con[child] < _con[child + 1])
				if (child + 1 < _con.size() && com(_con[child], _con[child + 1]))
				{
					child++;
				}
				//if(_con[parent] < _con[child])
				if(com(_con[parent] , _con[child]))
				{
					std::swap(_con[parent], _con[child]);
					parent = child;
					child = parent * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}
		void AdjustUp(int child)
		{
			Compare com;
			int parent = (child - 1) / 2;
			while (child > 0)
			{
				//if (_con[child] > _con[parent])
				if (com(_con[parent], _con[child]))
				{
					std::swap(_con[child], _con[parent]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}
		template<class InputIterator>
		priority_queue(InputIterator first,InputIterator last)
		{
			while (first != last)
			{
				_con.push_back(*first);
				++first;
			}
			for (int i = (_con.size()-1 - 1) / 2; i >= 0; --i)
			{
				AdjustDown(i);
			}
		}

		void push(const T& x)
		{
			_con.push_back(x);
			AdjustUp(_con.size()-1);
		}

		size_t size()
		{
			return _con.size();
		}

		bool empty()
		{
			return _con.empty();
		}

		T& top()
		{
			return _con[0];
		}

		void pop()
		{
			std::swap(_con[0], _con[size() - 1]);
			_con.pop_back();
			AdjustDown(0);
		}
	private:
		Container _con;
	};

	void test_priority_queue()
	{
		priority_queue<int,vector<int>,Greater<int>> pq;
//		priority_queue<int,vector<int>,Less<int>> pq;
		pq.push(1);
		pq.push(2);
		pq.push(3);
		pq.push(9);
		pq.push(5);
		pq.push(7);
		pq.push(4);

		while(!pq.empty())
		{
			cout<< pq.top() << " ";
			pq.pop();
		}
		cout << endl;
	}
}

